package handlers

import (
	"fmt"
	"strconv"
	"time"

	"sales-web/server/dal"

	"github.com/gin-gonic/gin"
)

func (h *Handler) CreateDispatchOrder(c *gin.Context) {
	user := GetCurrentUser(c)
	var request dal.CustomOrder
	err := c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	err = h.checkOrder(request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var country dal.Country
	err = h.dbc.Where("name=?", request.Country).First(&country).Error
	if err != nil {
		SendErrResp(c, 400, fmt.Errorf("country not found,err: %s", err))
		return
	}

	request.CostPrice = country.CostPrice
	request.DispatchUserID = user.ID
	request.OrderCreateTime = time.Now()
	err = h.dbc.Create(&request).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, request)
}

func (h *Handler) UpdateDispatchOrder(c *gin.Context) {
	idStr, _ := c.Params.Get("id")
	user := GetCurrentUser(c)
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		SendErrResp(c, 400, fmt.Errorf("faield to parse id, err:%s", err))
		return
	}
	var request dal.CustomOrder
	err = c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var item dal.CustomOrder
	err = h.dbc.Where("id= ?", id).First(&item).Error
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}

	if user.Role != "super_admin" && time.Now().Sub(item.CreatedAt).Hours() > 48 {
		SendErrResp(c, 500, fmt.Errorf("超过2天不能修改，创建时间%s", time.Now()))
		return
	}

	item.CustomerCount = request.CustomerCount
	item.CompleteCount = request.CompleteCount
	item.DispatchUserComment = request.DispatchUserComment
	err = h.dbc.Save(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, "")
}
